package cn.fl.sue.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.api.IMcrBillMApiService;
import cn.fl.project.condition.PrjPaySchMYqQC;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.condition.PrjPrdPaySchMQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPaySchMYqService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPaySchMYqVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.sue.api.ISueApplyDtlApiService;
import cn.fl.sue.api.ISysFlowSSueHApiService;
import cn.fl.sue.condition.SueApplyDtlQC;
import cn.fl.sue.condition.SueApplyInfoQC;
import cn.fl.sue.condition.SueApplyViewQC;
import cn.fl.sue.condition.SysFlowSSueHQC;
import cn.fl.sue.constant.SueConstant;
import cn.fl.sue.constant.SueDicCode;
import cn.fl.sue.constant.SueTableName;
import cn.fl.sue.dto.SueApplyDtlDTO;
import cn.fl.sue.dto.SueBillDTO;
import cn.fl.sue.dto.SueMcrBillDTO;
import cn.fl.sue.dto.SysFlowSSueHDTO;
import cn.fl.sue.service.ISueApplyInfoService;
import cn.fl.sue.service.ISueApplyViewService;
import cn.fl.sue.vo.SueApplyInfoVO;
import cn.fl.sue.vo.SueApplyViewDtlVO;
import cn.fl.sue.vo.SueApplyViewVO;
import cn.fl.sue.voTransform.SueApplyInfoVOTransform;
import cn.fl.system.service.ISysUlFilesRecService;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import fl.flow.facade.flow.api.IFlowApiService;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者:hongyanbo
 * 时间:2019-03-05
 */
@Controller
@RequestMapping("/sue/sueApplyInfo")
public class SueApplyInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(SueApplyInfoController.class);
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
    private ISueApplyViewService sueApplyViewService;
    @Autowired
    private IPrjPrdDtlService prjPrdDtlService;
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;
    @Autowired
    private ISueApplyInfoService sueApplyInfoService;
    @Autowired
    private ISueApplyDtlApiService sueApplyDtlApiService;
    @Autowired
    private IPrjPrdPaySchMService prjPrdPaySchMService;
    @Autowired
    private ISysFlowSSueHApiService sysFlowSSueHApiService;
    @Autowired
    private IFlowApiService flowApiService;
    @Autowired
    private IPrjBscInfoService prjBscInfoService;
    @Autowired
    private IMcrBillMApiService mcrBillMApiService;
    @Autowired
    private ISysUsrApiService sysUsrApiService;
    @Autowired
    private IPrjPaySchMYqService prjPaySchMYqService;

    /**
     * 诉讼申请列表
     * @param model
     * @return
     */
    @RequestMapping("/toListPage.do")
    public ModelAndView toListPage(ModelAndView model){
        model.setViewName("sue/sueApply/sueApplyInfoList");
        // 项目类型
        List<SysDictionaryDTO> prjTypCdList = this.sysDictionaryApiService.searchGroupAll("11000", "0000", "PRJ0002");
        List<SysDictionaryDTO> mcrPrjTypCdList = this.sysDictionaryApiService.searchGroup("11000", "0000", "MCR0001");
        List<SysDictionaryDTO> sueStsCdList = this.sysDictionaryApiService.searchGroup("11000", "0000", "SUE0007");
        prjTypCdList.addAll(mcrPrjTypCdList);
        model.addObject("sueStsCdList",sueStsCdList);
        model.addObject("prjTypCdList",prjTypCdList);
        model.addObject("currentUserId",CurrentThreadContext.getCurrentUserId());
        model.addObject("currOrg",CurrentThreadContext.getCurrentOrgCd());
        return model;
    }

    /**
     * 诉讼管理列表
     * @param model
     * @return
     */
    @RequestMapping("/toSueManageList.do")
    public ModelAndView toSueManageList(ModelAndView model){
        model.setViewName("sue/sueApply/sueManageList");
        // 项目类型
        List<SysDictionaryDTO> prjTypCdList = this.sysDictionaryApiService.searchGroupAll("11000", "0000", "PRJ0002");
        List<SysDictionaryDTO> mcrPrjTypCdList = this.sysDictionaryApiService.searchGroup("11000", "0000", "MCR0001");
        prjTypCdList.addAll(mcrPrjTypCdList);
        model.addObject("prjTypCdList",prjTypCdList);
        model.addObject("currentUserId",CurrentThreadContext.getCurrentUserId());
        model.addObject("currOrg",CurrentThreadContext.getCurrentOrgCd());
        return model;
    }

    /**
     * 初始化诉讼管理列表
     * @param page
     * @param pagesize
     * @param condition
     * @return
     */
    @RequestMapping("/initList.do")
    @ResponseBody
    public ListPageVO<SueApplyViewVO> initList(int page, int pagesize, SueApplyViewQC condition){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        pager.setCondition(condition);
        String prjTypCd = condition.getPrjTypCd();
        if(StringUtils.isBlank(prjTypCd)){
            condition.setPrjTypCd(null);
        }
        pager = sueApplyViewService.selectListPage(pager);
        List<SueApplyViewVO> resultList = (List<SueApplyViewVO>) pager.getResultList();

        return new ListPageVO<>(resultList,pager.getTotalCount());
    }

    /**
     * 诉讼申请列表
     * @param page
     * @param pagesize
     * @param condition
     * @return
     */
    @RequestMapping("/initApplyList.do")
    @ResponseBody
    public ListPageVO<SueApplyViewVO> initApplyList(int page, int pagesize, SueApplyViewQC condition){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        pager.setEveryPage(pagesize);
        pager.setCondition(condition);
        String prjTypCd = condition.getPrjTypCd();
        if(StringUtils.isBlank(prjTypCd)){
            condition.setPrjTypCd(null);
        }
        pager = sueApplyViewService.selectApplyListPage(pager);
        List<SueApplyViewVO> resultList = (List<SueApplyViewVO>) pager.getResultList();

        return new ListPageVO<>(resultList,pager.getTotalCount());
    }
    @RequestMapping("/initDtlList.do")
    @ResponseBody
    public ListPageVO<SueApplyViewDtlVO> initDtlList(Long dataId,String dataTable){

        List<SueApplyViewDtlVO> sueApplyViewDtlVOS = sueApplyViewService.selectDtlList(dataId, dataTable);

        return new ListPageVO<>(sueApplyViewDtlVOS,sueApplyViewDtlVOS.size());
    }

    /**
     * @return
     * @Author huangkailun
     * @Date 11:27 2019-10-31
     * @Description 对新发起的诉讼申请结案审批流程进行校验（存在历史诉讼申请或结案审批流程 在审核中，不允许发起新流程；历史的诉讼申请通过未发起结案审批，不允许发起新流程；不允许重复发起新流程）
     * @Param dataId 数据主键ID（项目ID、小贷账单ID、保险分期ID、垫款ID）
     */
    @RequestMapping("/checkSueApplyFLow.do")
    @ResponseBody
    public Object checkSueApplyFLow(Long dataId) {
        BaseLogUtils.newLogger(String.format("校验诉讼申请结案审批流程开始，dataId=",dataId)).info();
        DataResultVO result = new DataResultVO();
        result.setSuccess(BaseConstant.IS_YESNO_YES);
        if (StringUtils.isEmpty(dataId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("项目或小贷id为空，无法发起流程");
            return result;
        }
        // 当前项目底下的全部诉讼申请
        List<SueApplyInfoVO> sueApplyInfoVOS = this.sueApplyInfoService.selectByDataId(dataId);
        if (CollectionUtils.isNotEmpty(sueApplyInfoVOS)) {
            for (SueApplyInfoVO sueApplyInfoVO : sueApplyInfoVOS) {
                Long applyId = sueApplyInfoVO.getId();
                // 校验是否有旧的审核中的诉讼申请流程
                SysFlowSSueHQC sysFlowSSueHQC = new SysFlowSSueHQC();
                sysFlowSSueHQC.setDataId(applyId);
                sysFlowSSueHQC.setBusType(SueConstant.SUE_APPLY_TYP_061);
                List<String> audStsCdList = Lists.newArrayList();
                audStsCdList.add(SueConstant.AUD_STS_CD_1);
                audStsCdList.add(SueConstant.AUD_STS_CD_2);
                sysFlowSSueHQC.setAudStsCdList(audStsCdList);
                sysFlowSSueHQC.setIsDel(BaseConstant.IS_YESNO_NO);
                List<SysFlowSSueHDTO> sysFlowSSueHDTOS = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
                if (CollectionUtils.isNotEmpty(sysFlowSSueHDTOS)) {
                    for (SysFlowSSueHDTO sysFlowSSueHDTO : sysFlowSSueHDTOS) {
                        if (SueConstant.AUD_STS_CD_1.equals(sysFlowSSueHDTO.getAudStsCd())) {
                            result.setSuccess(BaseConstant.IS_YESNO_NO);
                            result.setInfo("存在历史的诉讼申请流程正在审核中，无法发起新的诉讼结案审批流程");
                            return result;
                        } else if (SueConstant.AUD_STS_CD_2.equals(sysFlowSSueHDTO.getAudStsCd())) {
                            sysFlowSSueHQC = new SysFlowSSueHQC();
                            sysFlowSSueHQC.setDataId(sysFlowSSueHDTO.getDataId());
                            sysFlowSSueHQC.setBusType(SueConstant.SUE_CASE_FINISHED_TYP);
                            sysFlowSSueHDTOS = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
                            if (CollectionUtils.isEmpty(sysFlowSSueHDTOS)) {
                                result.setSuccess(BaseConstant.IS_YESNO_NO);
                                result.setInfo("存在历史的诉讼申请流程已审核通过但无结案审批流程，无法发起新的诉讼结案审批流程");
                                return result;
                            }
                        }
                    }
                }
                // 校验是否有旧的审核中的结案审批流程
                sysFlowSSueHQC = new SysFlowSSueHQC();
                sysFlowSSueHQC.setDataId(applyId);
                sysFlowSSueHQC.setBusType(SueConstant.SUE_CASE_FINISHED_TYP);
                sysFlowSSueHQC.setAudStsCd(SueConstant.AUD_STS_CD_1);
                sysFlowSSueHQC.setIsDel(BaseConstant.IS_YESNO_NO);
                sysFlowSSueHDTOS = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
                if (CollectionUtils.isNotEmpty(sysFlowSSueHDTOS)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("存在历史的结案审批流程正在审核中，无法发起新的诉讼结案审批流程");
                    return result;
                }
                // 校验是否有已发起未通过的诉讼申请及结案审批流程
                sysFlowSSueHQC = new SysFlowSSueHQC();
                sysFlowSSueHQC.setDataId(applyId);
                sysFlowSSueHQC.setBusType(SueConstant.SUE_APPLY_CASE_FINISHED_TYP_069);
                sysFlowSSueHQC.setIsDel(BaseConstant.IS_YESNO_NO);
                sysFlowSSueHQC.setAudStsCd(SueConstant.AUD_STS_CD_1);
                sysFlowSSueHDTOS = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
                if (CollectionUtils.isNotEmpty(sysFlowSSueHDTOS)) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo("存在诉讼结案审批流程正在审核中，无法发起新的诉讼结案审批流程");
                    return result;
                }
            }
        }
        BaseLogUtils.newLogger(String.format("校验诉讼申请结案审批流程结束，dataId=%s,校验结果result：%s",dataId,JSON.toJSONString(result))).info();
        return result;

    }

    /**
     * @return
     * @Author huangkailun
     * @Date 15:31 2019-11-04
     * @Description
     * @Param
     */
    @RequestMapping("/toSueApplyAndCloseCasePage.do")
    public ModelAndView toSueApplyAndCloseCasePage(Long applyId, String taskFlag, String rmSvBtn) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("sue/sueApply/sueApplyAndCloseCasePage");
        modelAndView.addObject("applyId", applyId);
        modelAndView.addObject("taskFlag", taskFlag);
        modelAndView.addObject("rmSvBtn", rmSvBtn);
        return modelAndView;
    }

    /**
     * 诉讼申请
     * 诉讼申请(设备账单) or 诉讼申请（小额贷账单）
     * @param model
     * @param dataId
     * @param dataTable 数据表 这个参数控制使用哪个view
     * @param applyId 申请ID,这个参数控制是否为编辑页面
     * @param viewFlag  1:仅查看
     * @param lawyerNeedFlag  律师必填flag 非空表示必填
     * @param taskFlag  当前节点的flag，判断页面处理和校验
     * @return
     */
    @RequestMapping("/toAddPage.do")
    public ModelAndView toAddPage(ModelAndView model,Long dataId,String dataTable ,Long applyId,String viewFlag,String lawyerNeedFlag, String taskFlag, String rmSvBtn){
        if(applyId != null && applyId !=0L){
            SueApplyInfoVO dto = this.sueApplyInfoService.selectById(applyId);
            dataId = dto.getDataId();
            dataTable = dto.getDataTable();
            model.addObject("dto",dto);
        }
        if(StringUtils.isNotBlank(dataTable) && SueTableName.MCR_BILL_M.equals(dataTable)){
            model.setViewName("sue/sueApply/sueApplyAddMcr");
        }else{
            model.setViewName("sue/sueApply/sueApplyAdd");
        }
        // dic
        // SUE0001 违约类型
        List<SysDictionaryDTO> breachTypList = this.sysDictionaryApiService.searchGroup("11000", "0000", SueDicCode.SUE0001);
        //诉讼方式
        List<SysDictionaryDTO> sueWayList = this.sysDictionaryApiService.searchGroup("11000", "0000", SueDicCode.SUE0002);
        List<SysDictionaryDTO> yesNoList = this.sysDictionaryApiService.searchGroup("11000", "0000", "SYS0021");
        // 诉讼管辖
        List<SysDictionaryDTO> sueDomainList = this.sysDictionaryApiService.searchGroup("11000", "0000", SueDicCode.SUE0003);
        // 诉讼状态
        List<SysDictionaryDTO> sueStsCdList = this.sysDictionaryApiService.searchGroup("11000", "0000", SueDicCode.SUE0007);
        // 人员列表
        // 总部人员查询
        Pager page1 = new Pager();
        page1.setEveryPage(100);
        page1.setCurrentPage(1);
        SysUsrQueryCondition qc1 = new SysUsrQueryCondition();
        qc1.setSysCd("11000");
        qc1.setOrgId(17L); //风险管理部
        qc1.setRoleId(10016L); //法律事务律师
        page1.setCondition(qc1);
        Pager pager = this.sysUsrApiService.searchUsrByOrgIdRoleId(page1);
        List<SysUsrDTO> usrList1 = (List<SysUsrDTO>) pager.getResultList();
        // 属地人员查询
        Pager page2 = new Pager();
        page2.setEveryPage(100);
        page2.setCurrentPage(1);
        SysUsrQueryCondition qc2 = new SysUsrQueryCondition();
        qc2.setSysCd("11000");
        qc2.setOrgId(181011143002204L); //贷后管理中心
        qc2.setRoleId(10016L); //法律事务律师
        page2.setCondition(qc2);
        Pager pager2 = this.sysUsrApiService.searchUsrByOrgIdRoleId(page2);
        List<SysUsrDTO> usrList2 = (List<SysUsrDTO>) pager2.getResultList();
        if ("7".equals(taskFlag) || "8".equals(taskFlag)) {
            // 风险管理部结案审批 || 贷后管理中心结案审批
            viewFlag = "1";
        }
        model.addObject("breachTypList",breachTypList);
        model.addObject("taskFlag",taskFlag);
        model.addObject("rmSvBtn",rmSvBtn);
        model.addObject("sueWayList",sueWayList);
        model.addObject("yesNoList",yesNoList);
        model.addObject("sueStsCdList",sueStsCdList);
        model.addObject("sueDomainList",sueDomainList);
        model.addObject("dataId",dataId);
        model.addObject("lawyerNeedFlag",lawyerNeedFlag);
        model.addObject("applyId",applyId);
        model.addObject("usrNm", CurrentThreadContext.getCurrentUserName());
        model.addObject("now", DateUtils.getCurrentDateStr(DateUtils.YYYY_MM_DD));
        model.addObject("usrList1", usrList1);
        model.addObject("usrList2", usrList2);
        model.addObject("viewFlag",viewFlag);

        // TODO 查基本信息列表

        return model;
    }

    /**
     * 诉讼申请(设备账单)--基础信息
     * @param prjId
     * @return
     */
    @RequestMapping("initPrjPrdDtlList.do")
    @ResponseBody
    public ListPageVO initPrjPrdDtlList(@RequestParam Long prjId,Long applyId){
        PrjPaySchMYqQC yqCondition = new PrjPaySchMYqQC();
        yqCondition.setyPrjId(prjId);
        List<PrjPaySchMYqVO> yqList = this.prjPaySchMYqService.searchList(yqCondition);
        List<Long> prjIdList = yqList.stream().map(q -> q.getPrjId()).collect(Collectors.toList());
        if(prjIdList==null){
            prjIdList=new ArrayList<>();
        }
        prjIdList.add(prjId);
        PrjPrdDtlQueryCondition qc = new PrjPrdDtlQueryCondition();
        qc.setPrjIdList(prjIdList);
        qc.setIsDel(0);
        List<PrjPrdDtlVO> list = prjPrdDtlService.selectList(qc);
        // 查设备款
        List<Long> paySchIdList = new ArrayList<>();

        if(CollectionUtils.isNotEmpty(list)){
            for (PrjPrdDtlVO dtlVO : list) {
                paySchIdList.add(dtlVO.getPaySchId());
                //设置承租人名称
                if (StringUtils.isNotEmpty(dtlVO.getPrjId())){
                    CstBscInfoVO cstBscInfoVO = prjBscInfoService.getCstTypByPrjId(dtlVO.getPrjId());
                    dtlVO.setCstName(cstBscInfoVO == null ? null :cstBscInfoVO.getCstNm());
//                    dtlVO.setCstId(cstBscInfoVO.getCstUsrRVO().getCstId());
                    dtlVO.setCstId(cstBscInfoVO.getId());
                }
            }
        }

        // 支付表ID - 设备款
        Map<Long,Double> amtMap = new HashMap<>();
        if(CollectionUtils.isNotEmpty(paySchIdList)){
            PrjPrdPaySchMQueryCondition mqc = new PrjPrdPaySchMQueryCondition();
            mqc.setIdList(paySchIdList);
            mqc.setIsDel(0);
            List<PrjPrdPaySchMVO> paySchMList = prjPrdPaySchMService.searchList(mqc);

            if(CollectionUtils.isNotEmpty(paySchMList)){
                for (PrjPrdPaySchMVO mvo : paySchMList) {
                    amtMap.put(mvo.getId(),mvo.getTotLsItmAmt());
                }
            }
        }
        //设置设备款
        if(CollectionUtils.isNotEmpty(list)){
            for (PrjPrdDtlVO dtlVO : list) {
                Double aDouble = amtMap.get(dtlVO.getPaySchId());
                dtlVO.setMoney(aDouble);
                Date backDt = dtlVO.getBackDt();
                if(backDt != null){
                    dtlVO.setIsBack("是");
                    dtlVO.setBackDtString(DateUtils.formatDateToString(backDt,DateUtils.YYYY_MM_DD));
                }else{
                    dtlVO.setIsBack("否");
                }
                dtlVO.setIsYQ(0);
                if(CollectionUtils.isNotEmpty(yqList)){
                	for (PrjPaySchMYqVO i : yqList) {
						if(dtlVO.getPaySchId().equals(i.getYqPaySchId())){
							dtlVO.setIsYQ(1);
						}
					}
                }
            }
        }
        // 使用期限  GPS在线
        if(applyId != null){
            SueApplyDtlQC qc2 = new SueApplyDtlQC();
            qc2.setApplyId(applyId);
            List<SueApplyDtlDTO> dtlDTOList = this.sueApplyDtlApiService.selectList(qc2);
            Map<Long ,SueApplyDtlDTO> dtlMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(dtlDTOList)){
                for (SueApplyDtlDTO dtlDTO : dtlDTOList) {
                    dtlMap.put(dtlDTO.getPaySchId(),dtlDTO);
                }
            }
            if(CollectionUtils.isNotEmpty(list)){
                for (PrjPrdDtlVO dtlVO : list) {
                    SueApplyDtlDTO dtlDTO = dtlMap.get(dtlVO.getPaySchId());
                    if(dtlDTO!=null){
                        dtlVO.setUseTmLimit(dtlDTO.getUseTmLimit());
                        dtlVO.setIsGpsOnline(dtlDTO.getIsGpsOnline());

                    }
                }
            }

        }

        if(CollectionUtils.isNotEmpty(list)){
            return new ListPageVO<PrjPrdDtlVO>(list,list.size());
        }else{
            return null;
        }
    }
    /**
     * 诉讼申请(设备账单)--账单信息
     * 初始化账单列表
     * @return
     */
    @RequestMapping("/initBillList.do")
    @ResponseBody
    public ListPageVO initBillList(Long prjId){

        List<SueBillDTO> list = this.sueApplyViewService.selectBillList(prjId);
        if(CollectionUtils.isNotEmpty(list)){
            return new ListPageVO<SueBillDTO>(list,list.size());
        }else{
            return null;
        }
    }

    /**
     * 保存或修改并发起诉讼申请及结案审批流程
     */
    @RequestMapping("saveOrUpdate.do")
    @ResponseBody
    public DataResultVO saveOrUpdate(String dtlList, SueApplyInfoVO apply, String uploadParam) {
        DataResultVO res = new DataResultVO();
        try {
            Long id = null;
            if (apply != null) {
                id = apply.getId();
            }
            if (id != null) {
                //修改
                apply.setMdfTm(new Date());
                apply.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                sueApplyInfoService.modify(SueApplyInfoVOTransform.toDTO(apply));
            } else {
                // 新增
                apply.setApplyerId(CurrentThreadContext.getCurrentUserId());
                apply.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                apply.setApplyerOrgCd(CurrentThreadContext.getCurrentOrgCd());
                apply.setCrtTm(new Date());
                apply.setSueStsCd("0001");
                res.setSuccess(1);
                res.setInfo("新增成功");
                // 获取组织架构
                String orgCd = null;
                String dataTable = apply.getDataTable();
                if (SueTableName.PRJ_BSC_INFO.equals(dataTable)) {
                    PrjBscInfoVO prjBscInfoVO = prjBscInfoService.selectById(apply.getDataId());
                    if (prjBscInfoVO != null) {
                        orgCd = prjBscInfoVO.getCstMgrOrgCd();
                    }
                } else if (SueTableName.MCR_BILL_M.equals(dataTable)) {
                    orgCd = "0000";
                }
                if (StringUtils.isNotBlank(orgCd)) {
                    id = sueApplyInfoService.add(SueApplyInfoVOTransform.toDTO(apply));
                    // dtl add
                    if (StringUtils.isNotBlank(dtlList)) {
                        List<SueApplyDtlDTO> dtlDTOList = JSON.parseArray(dtlList, SueApplyDtlDTO.class);
                        for (SueApplyDtlDTO dto : dtlDTOList) {
                            dto.setSueApplyId(id);
                            dto.setMdfTm(null);
                            dto.setMdfUsrId(null);
                            sueApplyDtlApiService.add(dto);
                        }
                    }
                    FlowStartParamsDTO flowStartParamsDTO = this.sueApplyInfoService.getFlowStartParamsDTO(orgCd, orgCd.length() >= 8 ? orgCd.substring(0, 8) : orgCd, SueConstant.SUE_APPLY_CASE_FINISHED_TYP_069, id, "SUE_APPLY_INFO");
                    BaseLogUtils.newLogger(String.format("发起流程的参数为：",JSON.toJSONString(flowStartParamsDTO))).info();
                    flowApiService.noTransFlowStart(flowStartParamsDTO);
                } else {
                    throw new BaseException("缺少组织机构代码,无法发起流程。");
                }
            }
            if (id != null) {
                uploadAttchment(uploadParam, res, id);
            }
        } catch (BaseException e) {
            BaseLogUtils.newLogger(String.format("新增失败")).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0001);
            res.setInfo(e.getMessage());
            res.setSuccess(0);
        } catch (Exception e) {
            BaseLogUtils.newLogger(String.format("新增失败")).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0001);
            res.setInfo("新增失败，服务异常");
            res.setSuccess(0);
        }
        return res;
    }

    /**
     * 文件上传方法
     * @param attchmnt
     * @param result
     * @param id
     */
    private void uploadAttchment(String attchmnt, DataResultVO result, Long id) {
        if(StringUtils.isNotEmpty(attchmnt)){
            //上传解析
            try{
                String cfgCd = "SUE003";
                String cfgDtlCd = "10";
                String tabNm = "SUE_APPLY_INFO";
                String cfgOrgCd = "0000";
                Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, "附件下载!", null, null, false, cfgOrgCd);
                if(null == attchmntPass || attchmntPass == false){
                    result.setInfo(result.getInfo()+"-附件上传失败!");
                }
            }catch(Exception e){
                BaseLogUtils.newLogger(String.format("%s 附件上传失败",result.getInfo())).setThrowable(e).error(LogExceptionEnum.COMMON_CODE_0001);
                result.setInfo(result.getInfo()+"-附件上传失败!");
            }
        }
    }

    /**
     *  小贷账单
     * @param mcrId 小贷支付表ID
     * @return
     */
    @RequestMapping("/initMcrList.do")
    @ResponseBody
    public ListPageVO toMcrAddPage(@RequestParam Long mcrId){
        ArrayList<Object> list = new ArrayList<>();
        SueMcrBillDTO dto = this.sueApplyViewService.selectMcrBill(mcrId);
        list.add(dto);
        if(CollectionUtils.isNotEmpty(list)){
            return new ListPageVO(list,list.size());
        }
        return null;
    }

    /**
     *  诉讼申请流程历史-列表页面
     * @param model
     * @param applyId 申请ID
     * @return
     */
    @RequestMapping("toSueApplyFlowHisListPage.do")
    public ModelAndView toSueApplyFlowHisListPage(ModelAndView model,Long applyId){
        model.setViewName("sue/sueApply/sueApplyFlowList");
        model.addObject("applyId",applyId);
        return model;
    }

    /**
     * 初始化数据
     * @param applyId
     * @return
     */
    @RequestMapping("initSueApplyFlowHisList.do")
    @ResponseBody
    public ListPageVO initSueApplyFlowHisList(@RequestParam Long applyId){
        SueApplyInfoVO sueApplyInfoVO = this.sueApplyInfoService.selectById(applyId);
        List<SysFlowSSueHDTO> list = new ArrayList<>();
        if(sueApplyInfoVO != null){
            List<SueApplyInfoVO> voList = this.sueApplyInfoService.selectByDataId(sueApplyInfoVO.getDataId());
            List<Long> applyIdList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(voList)){
                for (SueApplyInfoVO applyInfoVO : voList) {
                    applyIdList.add(applyInfoVO.getId());
                }
            }
            if(CollectionUtils.isNotEmpty(applyIdList)){
                SysFlowSSueHQC qc = new SysFlowSSueHQC();
                qc.setDataIdList(applyIdList);
                list = sysFlowSSueHApiService.selectList(qc);
            }
        }

        ;
        if(CollectionUtils.isNotEmpty(list)){
           return new ListPageVO(list,list.size());
        }
        return null;
    }

}
